#本文件是环境、界面、显示、其他操作等相关方法
import pygame
import random
import os
import time

#界面大小,可设置界面大小
SCREEN_X = 600
SCREEN_Y = 600

#默认游戏休闲模式
CasualMode = False

#最高分
historyBestScore = list()

#旋转度数
RIGHT   =   90
DOWN    =   180
LEFT    =   270

#一次性事件标志
onceFlag = {
    "DeathWarning": True,
    "ReadScores": True,
}

#贴图素材
IMG_score = pygame.image.load("image/font/scores.png")
IMG_body = pygame.image.load("image/font/body.png")
IMG_speed = pygame.image.load("image/font/speed.png")
gameover = pygame.image.load("image/font/gameover.png")
bestscore = pygame.image.load("image/font/bestScore.png")
casual = pygame.image.load("image/font/casualmode.png")
flabby = pygame.image.load("image/font/flabbymode.png")
walls = pygame.image.load('image/wall.png')
title = pygame.image.load("image/title.ico")
dust = pygame.image.load('image/background2.png')
dusts = [
        dust,
        pygame.transform.rotate(dust, LEFT),
        pygame.transform.rotate(dust, DOWN),
        pygame.transform.rotate(dust, RIGHT),
]
grass2 = pygame.image.load('image/grass2.png')
grass1 = pygame.image.load('image/grass1.png')
grass = [
    [
        grass1,
        pygame.transform.rotate(grass1, LEFT),
        pygame.transform.rotate(grass1, DOWN),
        pygame.transform.rotate(grass1, RIGHT),
    ],
    [
        grass2,
        pygame.transform.rotate(grass2, RIGHT),
        pygame.transform.rotate(grass2, DOWN),
        pygame.transform.rotate(grass2, LEFT),
    ]
]
num0 = pygame.image.load('image/number/0.png')
num1 = pygame.image.load('image/number/1.png')
num2 = pygame.image.load('image/number/2.png')
num3 = pygame.image.load('image/number/3.png')
num4 = pygame.image.load('image/number/4.png')
num5 = pygame.image.load('image/number/5.png')
num6 = pygame.image.load('image/number/6.png')
num7 = pygame.image.load('image/number/7.png')
num8 = pygame.image.load('image/number/8.png')
num9 = pygame.image.load('image/number/9.png')
number = [num0, num1, num2, num3, num4, num5, num6, num7, num8, num9]

#声音素材
pygame.mixer.init()
sod_eat1 = pygame.mixer.Sound("sound/eat1.wav")             #吃脆的东西
sod_eat2 = pygame.mixer.Sound("sound/eat2.wav")             #吃其他的东西
sod_eat3 = pygame.mixer.Sound("sound/eat3.wav")             #吃火箭
sod_eat4 = pygame.mixer.Sound("sound/eat4.wav")             #吃鸟
sod_over = pygame.mixer.Sound("sound/gameover.wav")         #吃其他的东西
sod_background = pygame.mixer.music.load("sound/background.mp3")


#事件标志位初始化
def flagInit():
    for flag in onceFlag.keys():
        onceFlag[flag] = True

#一次性事件
def do_once(fun, flag):
    if onceFlag[flag]:
        fun()
        onceFlag[flag] = False

#显示背景
def show_background(screen):
    screen.fill((112, 197, 206))
    for x in range(SCREEN_X//100):
        screen.blit(dusts[3], (x * 100, 0))
    for x in range(SCREEN_X//100):
        screen.blit(dusts[1], (x * 100, SCREEN_Y - 75))
    for y in range(SCREEN_Y//100):
        screen.blit(dusts[2], (0, y * 100))
    for y in range(SCREEN_Y//100):
        screen.blit(dusts[0], (SCREEN_X - 75, y * 100))

#画草皮
def show_grass(screen):
    screen.blit(grass[0][0], (0, SCREEN_Y - 25))
    screen.blit(grass[0][1], (0, 0))
    screen.blit(grass[0][2], (SCREEN_X - 25, 0))
    screen.blit(grass[0][3], (SCREEN_X - 25, SCREEN_Y -25))
    for x in range(SCREEN_X//50-1):
        screen.blit(grass[1][0], (x*50+25, SCREEN_Y-25))
    for x in range(SCREEN_X//50-1):
        screen.blit(grass[1][2], (x*50+25, 0))
    for x in range(SCREEN_X//50-1):
        screen.blit(grass[1][1], (SCREEN_X-25, x*50+25))
    for x in range(SCREEN_X//50-1):
        screen.blit(grass[1][3], (0, x*50+25))

#获取最高分
def get_rank(score = 0, speed = 0, lenBody = 0):
    global historyBestScore
    #打开一次文件
    if onceFlag["ReadScores"]:
        if not os.path.isfile(".data/history"):
            f = open(".data/history",'w')
            f.close()
        f = open(".data/history",'rb')
        #打开历史数据，读4次，分别是休闲模式最高分、flabby模式最高分，最快速度, 最长体长
        for i in range(4):
            historyBestScore.append(int.from_bytes(f.read(4),'big'))
        f.close()
        onceFlag["ReadScores"] = False

    #如果当前分数比历史高,则保存
    if CasualMode:
        #如果是休闲模式，仅仅比较分数
        if score > historyBestScore[0]:
            f = open(".data/history",'wb')
            historyBestScore[0] = score
            for i in historyBestScore:
                f.write(i.to_bytes(4,'big'))
            f.close()
    else:
        needSave = False
        #如果是flabby模式，比较speed，体长
        if score > historyBestScore[1]:
            historyBestScore[1] = score
            needSave = True
        if speed > historyBestScore[2]:
            historyBestScore[2] = speed
            needSave = True
        if lenBody > historyBestScore[3]:
            historyBestScore[3] = lenBody
            needSave = True
        if needSave:
            f = open(".data/history",'wb')
            for i in historyBestScore:
                f.write(i.to_bytes(4,'big'))
            f.close()
    return historyBestScore

# #显示文字方法   
# def show_text(screen, pos, text, color, font_bold = False, font_size = 50, font_italic = False):   
#     #获取系统字体，并设置文字大小  
#     cur_font = pygame.font.SysFont("Small Fonts", font_size)  
#     #设置是否加粗属性  
#     cur_font.set_bold(font_bold)  
#     #设置是否斜体属性  
#     cur_font.set_italic(font_italic)  
#     #设置文字内容  
#     text_fmt = cur_font.render(text, 1, color)  
#     #绘制文字  
#     screen.blit(text_fmt, pos)

#游戏结束显示信息
def show_overinfo(screen, score, speed, lenBody):
    x = SCREEN_X//2 - 300//2
    y = SCREEN_Y//2 - SCREEN_Y//5
    screen.blit(gameover, (x, y))
    get_rank(score, speed, lenBody)
    if CasualMode:
        screen.blit(bestscore, (x + 25, y + 80))
        show_number(screen, historyBestScore[0], (x + 110, y + 150))
    else:
        screen.blit(bestscore, (SCREEN_X-250-75, SCREEN_Y - 280))
        show_number(screen, historyBestScore[1], (SCREEN_X - 240, SCREEN_Y - 220))
        show_number(screen, historyBestScore[2], (SCREEN_X - 240, SCREEN_Y - 170))
        show_number(screen, historyBestScore[3], (SCREEN_X - 240, SCREEN_Y - 120))


#显示数字
def show_number(screen, num, startPosi):
    j = 0
    for i in str(num):
        screen.blit(number[int(i)], (startPosi[0]+25*j, startPosi[1]))
        j+=1

#划线
def draw_line(screen, x, y, x1, y1):
    pygame.draw.line(screen, (255, 255, 255), (x, y), (x1, y1), 5)

#显示按钮
def show_button(screen):
    x = SCREEN_X//2 - 250//2
    #y = SCREEN_Y//2 - 84//2
    y = SCREEN_Y//2 - SCREEN_Y//7
    screen.blit(casual, (x, y))
    screen.blit(flabby, (x, y - 77))
    if not CasualMode:
        pygame.draw.rect(screen, (255,255,255), (x,y - 77, 245,78), 8)
    else:
        pygame.draw.rect(screen, (255,255,255), (x,y, 245,78), 8)
    draw_line(screen,x - 50 ,y + 120, x + 300, y + 120)

#显示记录
def show_record(screen):
    startpos = SCREEN_X//2 - 240//2
    endpos = SCREEN_Y//2 - 80//2 + 75
    screen.blit(bestscore, (startpos, endpos))
    if not CasualMode:
        show_number(screen, historyBestScore[1],(startpos+80, endpos+65))
    else:
        show_number(screen, historyBestScore[0], (startpos+80, endpos+65))
    
#设置游戏模式
def set_mode(mode):
    global CasualMode
    CasualMode = mode
    
#获取当前游戏模式
def Casualmode():
    return CasualMode

def show_wall(screen, wall):
    for w in wall.wallpos:
        screen.blit(walls, w)

#墙种类集合
wallSet = (
[(SCREEN_X//2, 25*5, SCREEN_X//2, SCREEN_Y-25*5)],
[(SCREEN_X//2, 25*5, SCREEN_X//2, SCREEN_Y-25*5),(25*5, SCREEN_Y//2, SCREEN_X-25*5, SCREEN_Y//2),],
[(SCREEN_X//3//25*25, 25*5, SCREEN_X//3//25*25, SCREEN_Y-25*5),(SCREEN_X//3//25*25*2, 25*5, SCREEN_X//3//25*25*2, SCREEN_Y-25*5),],
# [(SCREEN_X//3, 25*5, SCREEN_X//3, SCREEN_Y-25*5),(SCREEN_X//3*2, 25*5, SCREEN_X//3*2, SCREEN_Y-25*5),],
)

# 墙类
class Wall(object):
    def __init__(self):
        self.wallpos = []
        self.addWall()

    def addWall(self):
        walldata = random.choice(wallSet)
        for pos in walldata:
            if pos[0]==pos[2]:
                for y in range(pos[1], pos[3] + 1,25):
                    self.wallpos.append(pygame.Rect(pos[0], y, 25, 25))
            elif pos[1] == pos[3]:
                for x in range(pos[0], pos[2]+ 1, 25):
                    self.wallpos.append(pygame.Rect(x, pos[1], 25, 25))

                
